<template>
  <Modal
    title="分配角色"
    :value="visible"
    :mask-closable="false"   width="850"
    :closable="false"
  >
    <!--头部插槽-->
    <p slot="header">
      <Icon type="ios-eye"></Icon>
      <span class="text-primary">分配用户: <span class="select-title">{{account}}</span> 角色</span>
    </p>
    <Row class="tree-menu">
      <Tree ref="menuTree" show-checkbox :data="menuTree" :render="renderContent"  :check-strictly='true'/>
      <Spin size="large" fix v-if="spinShow"></Spin>
    </Row>

    <div slot="footer">
      <Button size="default" @click="toggleSelected(menuTree,checkedAll)">全选/反选</Button>
      <Dropdown @on-click="dispatchActions" class="space-left-mini">
        <Button size="default" type="default">
          更多操作
          <Icon type="ios-arrow-down"/>
        </Button>
        <DropdownMenu slot="list">
          <DropdownItem v-for="item in dropDownSelect" value="item.value" :name="item.value" :key="item.value">{{
            item.label }}
          </DropdownItem>
        </DropdownMenu>
      </Dropdown>
      <Button size="default" @click="close" style="margin-left: 8px">取消</Button>
      <Button type="primary" size="default" style="margin-left: 8px" @click="submit()">提交</Button>
    </div>

  </Modal>
</template>

<script>
    import {getUserRoleTree} from '@/api/role';
    import {setUserRoles} from '@/api/userList';
    export default {
        name: "UserRole",
        data(){
            return {
                visible: false,
                row:{},
                account:'',
                searchWord: "",
                expandLevel: "",
                spinShow: false,
                menuTree: [],
                checkedAll: true,
                dropDownSelect: [
                    {
                        value: 'refresh',
                        label: '刷新',
                    },
                    {
                        value: 'rollall',
                        label: '收合所有',
                    },
                    {
                        value: 'openone',
                        label: '仅展开一级'
                    },
                    {
                        value: 'opentwo',
                        label: '仅展开两级'
                    },
                    {
                        value: 'openall',
                        label: '展开所有'
                    }
                ],

            }
        },
        methods: {
            open(row){
                this.visible =true;
                this.row = row
                this.account = row.account;
                this.initMenuNodes();
            },
            initMenuNodes() {
                this.checkedAll = true;
                this.spinShow = true;
                this.menuTree = [];
                let menuName = this.searchWord;
                let userId = this.row.id;
                debugger;
                getUserRoleTree({userId}).then(res => {
                    this.spinShow = false;
                    const data = res.data.data;
                    this.menuTree.push(...data);
                }).catch(err => {
                    this.spinShow = false;
                    console.error("获取菜单列表信息出错! " + err)
                })
            },
            submit() {
                let roleIds = this.geCheckedMenuIds().join(",");
                let userId = this.row.id;
                setUserRoles({userId, roleIds}).then(res => {
                    let data = res.data;
                    let message = data.message;
                    let code = data.code;
                    if (code === 200) {
                        this.$Message.success({
                                content: '角色分配成功',
                                duration: 3,
                                closable: true
                            }
                        );
                        this.visible = false;
                        this.$emit('ok');
                    }else{
                        this.$Message["error"]({background: true,duration: 3,
                            closable: true, content: message});
                    }
                }).catch(err => {
                    console.error("保存菜单权限时，出现错误" + err)
                })
            },
            geCheckedMenuIds() {
                let checkedNodes = this.$refs.menuTree.getCheckedNodes();
                const menuIds = [];
                checkedNodes.forEach(item => {
                    if (item) menuIds.push(item.id);
                });
                return menuIds;
            },
            close() {
                this.visible = false;
            },
            refreshNodes() {
                this.initMenuNodes(this.searchWord);
            },
            /**
             *  收合所有
             * @param treeNodes  当前的菜单树
             * @param type rollall openone opentwo openall
             */
            roll(treeNodes, type) {
                if (!!treeNodes) {
                    treeNodes.forEach(node => {
                        this.expandLevel = node.level;
                        node.expand = false;
                        if (type === 0) {
                            node.expand = false;
                        } else {
                            if (this.expandLevel > (type - 1)) {
                                return;
                            }
                            node.expand = true;
                        }
                        if (node.children && node.children.length > 0) {
                            this.roll(node.children, type)
                        }
                    });
                }
                this.expandLevel = "";
            },
            dispatchActions(name) {
                //请求分发
                switch (name) {
                    case "refresh":
                        this.refreshNodes();
                        break;
                    case "rollall":
                        this.roll(this.menuTree, 0);
                        break;
                    case "openone":
                        this.roll(this.menuTree, 1);
                        break;
                    case "opentwo":
                        this.roll(this.menuTree, 2);
                        break;
                    case "openall":
                        this.roll(this.menuTree, 3);
                        break;
                    default:
                        this.$Message["info"]({background: true, content: '正在努力开发中...'});
                        break;
                }
            },
            renderContent(h, {root, node, data}) {
                let level = node.node.level;
                return h('span', {
                    style: {
                        display: 'inline-block',
                        width: '100%'
                    }
                }, [
                    h('span', [
                        h('Icon', {
                            props: {
                                type: level === 0 ? 'md-paper-plane' : level === 1 || level === 2 ? 'md-reorder' : level === 3 ? 'md-radio-button-on' : 'ios-help-circle-outline'
                            },
                            style: {
                                marginRight: '8px'
                            }
                        }),
                        h('span',
                            {
                                style: {
                                    display: "inline-block",
                                    cursor: "pointer",
                                    background: node.node.selected ? "#d5e8fc" : "#fff", //根据选中状态设置样式
                                    color: node.node.selected ? "#515a6e" : "#515a6e",
                                    borderRadius: "3px",
                                    padding: "3px"
                                },
                                on: {
                                    click: () => {
                                        debugger
                                        if (!node.node.selected)
                                            this.$refs.menuTree.handleSelect(node.nodeKey); //手动选择树节点
                                    }
                                }
                            }, data.title)
                    ])

                ]);
            },
            toggleSelected(menuTree, checkVal) {
                menuTree.forEach((item) => {
                    // 选中值
                    item.checked = checkVal;
                    // 如果有子节点，递归
                    if (item.children) {
                        this.toggleSelected(item.children, checkVal);
                    }
                });
                this.checkedAll = !checkVal;
            }
        },

    }
</script>

<style lan="stylus" rel="stylesheet/stylus">

</style>
